<?php

namespace app\api\controller\common;

use Generator;
use think\Controller;
//use vendor\Tcpdf\tcpdf;
use think\Db;


/**
 * suntongjian专用类
 * 内部调用，非接口类
 */
class Commonpdf extends Controller
{

    //根据展会id查询动态展商表
    public function getTabName($exhibition_id)
    {
        $result = db('exhibition')->where(['id' => $exhibition_id])->find();
        $tabName = "";
        if ($result) {
            $tabName = $result['create_tablename'];
        } else {
            return json(['code' => 0, 'msg' => '缺少关键字段', 'data' => '']);
        }
        return $tabName;
    }


    public function getTabName1($exhibition_id){
        $result=db('exhibition')->where(['id'=>$exhibition_id])->find();
        $tabName='';
        if($result){
            $tabName=$result['create_person_table'];
        }else{
            return json(['code'=>0,'msg'=>'缺少关键字段','data'=>'']);
        }
        return $tabName;
    }

    public function cratePdf(){
        if (request()->isPost()) {
            $exhibition_id =$this->request->param('exhibition_id');
            $page =$this->request->param('excelPage');
            $page=$page>=1?$page:1;
            $exhibition=db('exhibition')->where(['id'=>$exhibition_id,'is_delete'=>0])->find();
            if(!$exhibition){
                return json(['code'=>0,'msg'=>'展会信息错误']);
            }
            $list=$this->export($exhibition_id,$page,50);
            if(count($list)==0){
                return json(array('code' => '0', 'msg' => '暂无数据'));
            }
            $res=$this->pdf($list,$exhibition['project_id']);
            return json($res);
        }else{
            return json(array('code' => '0', 'msg' => '请求失败'));
        }
    }

    public function export($exhibition_id,$page,$pageSize)
    {
        $tabNames=$this->getTabName($exhibition_id);
        $tabName='crm_'.$tabNames;
        $sql2="select p.* ,z.number as both_num,z.area as both_area,h.title as hall_title,gz.intro_en,gz.intro,gz.title";
        $sql2.=" from ".$tabName." as p ";
        $sql2.=" LEFT JOIN (SELECT max(id),agent_id,number,hall_id,area FROM crm_booth WHERE is_delete=0 and exhibition_id=$exhibition_id group by agent_id) as z on z.agent_id=p.id";
        $sql2.=" left join crm_hall as h on z.hall_id=h.id";
        $sql2.=" LEFT JOIN (select max(id) as goods_id,intro,intro_en,title,id_zs from crm_zsgoodszp where exhibition_id=$exhibition_id and intro is not null group by id_zs ) gz on gz.id_zs=p.id ";
        $sql2.=" where p.label=1";
        $sql2.=" order by h.title desc";
        $sql2.=" limit ".(($page-1)*$pageSize).",".$pageSize;
        $list=Db::query($sql2);
        $list_news = array_chunk($list,2);
        return $list_news;
    }

    public function crateUserPdf(){
        if (request()->isPost()) {
            $exhibition_id =$this->request->param('exhibition_id');
            $page =$this->request->param('excelPage');
            $exhibition=db('exhibition')->where(['id'=>$exhibition_id,'is_delete'=>0])->find();
            if(!$exhibition){
                return json(['code'=>0,'msg'=>'展会信息错误']);
            }
            $list=$this->userExport($exhibition_id);
            if(count($list)==0){
                return json(array('code' => '0', 'msg' => '暂无数据'));
            }
            $res=$this->pdfUser($list,$exhibition['project_id']);
            return json($res);
        }else{
            return json(array('code' => '0', 'msg' => '请求失败'));
        }
    }

    public function userExport($exhibition_id)
    {
        $tabNames=$this->getTabName1($exhibition_id);
        $list=db($tabNames)->field('company_name,name_cn,name_en,mobile_person,label,positions_cn,positions_en,email')->where(['label'=>1])->select();
        $company_list=db($tabNames)->Distinct(true)->field('company_name')->where(['label'=>1])->select();
        $result=[];
        if(count($list)>0){
            foreach ($company_list as &$v) {
                $company_name=$v['company_name'];
                $newArray=['company_name'=>$company_name,'child'=>array()];
                foreach ($list as &$vv) {
                    if($company_name == $vv['company_name']){
                        $newArray['child'][]=$vv;
                    }
                }
                $result[]=$newArray;
            }

        }
        $list_news = array_chunk($result,2);
        return $list_news;
    }





    /**
     * 生成pdf 展商名录
     * @param  string $html      需要生成的内容
     */

    public function pdf($list,$project_id){
        define('K_PATH_IMAGES', ROOT_PATH."public/poster/");
        vendor('Tcpdf.tcpdf');
        $pdf = new \Tcpdf('P', 'mm', 'A4', true, 'UTF-8', false);
        // 设置打印模式,设置文档信息
        $pdf->SetCreator(PDF_CREATOR);
        $pdf->SetAuthor('Nicola Asuni');
        $pdf->SetTitle('电子会刊');
        $pdf->SetSubject('TCPDF Tutorial');
        $pdf->SetKeywords('TCPDF, PDF, PHP, example, test, guide');
        // 是否显示页眉和是否显示页脚
        $pdf->setPrintHeader(true);
        $pdf->setPrintFooter(true);
        // 设置页眉和页脚信息内容
        $header_top=$project_id==21?'headertop2.jpg':'headertop1.jpg';
        $pdf->SetHeaderData($header_top, 190, '', '', array(0,64,255), array(0,64,128));
        // 设置页眉和页脚字体
        $pdf->setHeaderFont(Array('dejavusans', '', '12'));
        $pdf->setFooterFont(Array('dejavusans', '', '10'));
        // 设置间距
        $pdf->SetHeaderMargin('5');
        $pdf->SetFooterMargin('10');
        // 设置左、上、右的间距
        $pdf->SetMargins('5', '16', '5',true);
        // 设置是否自动分页  距离底部多少距离时分页
        $pdf->SetAutoPageBreak(true, '15');

        // 设置默认等宽字体
        $pdf->SetDefaultMonospacedFont('courier');
        // 设置行高
        $pdf->setCellHeightRatio(1);
        // 设置图像比例因子
        $pdf->setImageScale(1.25);
        //设置默认字体子集模式
        $pdf->setFontSubsetting(true);
        // 设置字体
        $pdf->SetFont('stsongstdlight', '', 14, '', true);
        $pdf->AddPage();

        for($i=0;$i<count($list);$i++){
            $html='<table width="100%" cellpadding="9" cellspacing="0">';
            $ddd=$this->getHtml($list[$i]);
            $html.=$ddd;
            $html.='</table>';
            $pdf->writeHTMLCell(0, 0, '', '', $html, 0, 1, 0, true, '', true);
            if ($i < count($list) - 1) {
                $pdf->AddPage();
            }
        }
        //PDF输出   I：在浏览器中打开，D：下载，F：在服务器生成pdf ，S：只返回pdf的字符串
        $nowDateCode=date("Ymd");
        $filName=ROOT_PATH.'public/uploads/pdf/'.$nowDateCode;
        $flag=false;
        if(!is_dir($filName)){
            $dir = iconv("UTF-8", "GBK", $filName);
            if (!file_exists($dir)){
                mkdir ($dir,0777,true);
                $flag=true;
            }
        }else{
            $flag=true;
        }
        if(!$flag){
            return array('code' => 0, 'msg' => '文件夹创建失败', 'data' => '');
        }
        $pdfName='/'.'down'.time().'.pdf';
//       $res=$pdf->Output('开标说明'.'.pdf', 'I');
        $res=$pdf->Output($filName.$pdfName, 'F');
        if(!$res){
            return array('code' => 1, 'msg' => '生成成功', 'data' => $nowDateCode.$pdfName);
        }
        return array('code' => 0, 'msg' => '生成成功', 'data' => '');
    }

    public  function getHtml($data){
        $leftData=array();$rightData=array();
        if(count($data)>=1){
            $leftData=is_array($data[0])?$data[0]:[];
        }
        if(count($data)>1){
            $rightData=is_array($data[1])?$data[1]:[];
        }
//        $html="<tr><td colspan='4' style='padding:20px;'></td></tr>";
        $html='<tr>';
        if(count($leftData)>0){
            $html.='<td width="20%">';
            $html.='<p style="font-size:14px;">'.$leftData['hall_title'].'-'.$leftData['both_num'].'</p>';
            $html.='<p style="font-size:12px;margin:0;">'.$leftData['country'].'&nbsp;&nbsp;&nbsp;&nbsp;'.$leftData['area_city'].'</p>';
            $html.='<p style="font-size:12px;margin:0;">地址：'.$leftData['company_address'].'</p>';
            $html.='<p style="font-size:12px;margin:0;">联系人：'.$leftData['name_cn'].'</p>';
            $html.='<p style="font-size:12px;margin:0;">tel：'.$leftData['tel'].'</p>';
            $html.='<p style="font-size:12px;padding-bottom:30px;">email：'.$leftData['email'].'</p>';
            $html.='</td>';
            $html.='<td width="30%">';
            $html.='<p style="font-size:14px;margin:0;font-weight: bold;height: 30px;line-height: 15px;">'.$leftData['company_name'].'</p>';
            $html.='<p style="font-size:12px;margin:0;font-weight: bold;">公司介绍</p>';
//            $html.='<p style="font-size:12px;margin:0;line-height: 18px;">'.$leftData['company_describe_en'].'</p>';
            $html.='<p style="font-size:12px;margin:0;line-height: 18px;">'.mb_substr($leftData['company_describe'],0,400).'</p>';
            $html.='<p style="font-size:12px;margin:0;font-weight: bold;">展品介绍</p>';
            $html.='<p style="font-size:12px;margin:0;font-weight: bold;">'.$leftData['title'].'</p>';
//            $html.='<p style="font-size:12px;margin:0;line-height: 18px;">'.$leftData['intro'].'</p>';
            $html.='<p style="font-size:12px;padding-bottom:30px;margin:0;line-height: 24px;">'.mb_substr($leftData['intro_en'],0,400).'</p>';
            $html.='</td>';
        }
        if(count($rightData)>0){
            $html.='<td width="20%">';
            $html.='<p style="font-size:14px;">'.$rightData['hall_title'].'-'.$rightData['both_num'].'</p>';
            $html.='<p style="font-size:12px;margin:0;">'.$rightData['country'].'&nbsp;&nbsp;&nbsp;&nbsp;'.$rightData['area_city'].'</p>';
            $html.='<p style="font-size:12px;margin:0;">地址：'.$rightData['company_address'].'</p>';
            $html.='<p style="font-size:12px;margin:0;">联系人：'.$rightData['name_cn'].'</p>';
            $html.='<p style="font-size:12px;margin:0;">tel：'.$rightData['tel'].'</p>';
            $html.='<p style="font-size:12px;padding-bottom:30px;">email：'.$rightData['email'].'</p>';
            $html.='</td>';
            $html.='<td width="30%">';
            $html.='<p style="font-size:14px;margin:0;font-weight: bold;height: 30px;line-height: 15px;">'.$rightData['company_name'].'</p>';
            $html.='<p style="font-size:12px;margin:0;font-weight: bold;">公司介绍</p>';
//            $html.='<p style="font-size:12px;margin:0;line-height: 18px;">'.$rightData['company_describe_en'].'</p>';
            $html.='<p style="font-size:12px;margin:0;line-height: 18px;">'.mb_substr($leftData['company_describe'],0,400).'</p>';
            $html.='<p style="font-size:12px;margin:0;font-weight: bold;">展品介绍</p>';
            $html.='<p style="font-size:12px;margin:0;font-weight: bold;">'.$rightData['title'].'</p>';
//            $html.='<p style="font-size:12px;margin:0;line-height: 18px;">'.$rightData['intro'].'</p>';
            $html.='<p style="font-size:12px;padding-bottom:30px;margin:0;line-height: 18px;">'.mb_substr($leftData['intro_en'],0,400).'</p>';
            $html.='</td>';
        }
        $html.='</tr>';
        return $html;
    }



    /**
     * 生成pdf 展商名录
     * @param  string $html      需要生成的内容
     */

    public function pdfUser($list,$project_id){
        define('K_PATH_IMAGES', ROOT_PATH."public/poster/");
        vendor('Tcpdf.tcpdf');
        $pdf = new \Tcpdf('P', 'mm', 'A4', true, 'UTF-8', false);
        // 设置打印模式,设置文档信息
        $pdf->SetCreator(PDF_CREATOR);
        $pdf->SetAuthor('Nicola Asuni');
        $pdf->SetTitle('买家名录');
        $pdf->SetSubject('TCPDF Tutorial');
        $pdf->SetKeywords('TCPDF, PDF, PHP, example, test, guide');
        // 是否显示页眉和是否显示页脚
        $pdf->setPrintHeader(true);
        $pdf->setPrintFooter(true);
        $pdf->Rect(10, 10, $pdf->getPageWidth(), $pdf->getPageHeight()-20,
            'DF', "",  array(220, 220, 200));
        // 设置页眉和页脚信息内容
        $header_top=$project_id==21?'mjplftop.jpg':'mjplftop1.jpg';
        $pdf->SetHeaderData($header_top, 200, '', '', array(0,64,255), array(0,64,128));
        $pdf->setFooterData(array(0,64,0), array(0,64,128));
        // 设置页眉和页脚字体
        $pdf->setHeaderFont(Array('dejavusans', '', '12'));
        $pdf->setFooterFont(Array('dejavusans', '', '10'));
        // 设置间距
        $pdf->SetHeaderMargin('5');
        $pdf->SetFooterMargin('8');
        // 设置左、上、右的间距
        $pdf->SetMargins('5', '18', '5');
        // 设置是否自动分页  距离底部多少距离时分页
        $pdf->SetAutoPageBreak(true, 10);
//        $pdf->setCellPaddings(0, 0, 0, 20);
        // 设置默认等宽字体
        $pdf->SetDefaultMonospacedFont('courier');
        // 设置行高
        $pdf->setCellHeightRatio(1);
        // 设置图像比例因子
        $pdf->setImageScale(1.25);
        //设置默认字体子集模
        // 设置字体
        $pdf->SetFont('stsongstdlight', '', 14, '', true);
        $pdf->AddPage();
        $html='<table width="100%" cellpadding="8" cellspacing="0">';
        for($i=0;$i<count($list);$i++){
            $ddd=$this->getHtmlUser($list[$i],$i);
            $html.=$ddd;
        }
        $html.='</table>';
//        $pdf->writeHTMLCell(0, 0, '', '', $html, 0, 1, 0, true, '', true);
        $pdf->writeHTML($html, true, false, true, false, '');
        $pdf->lastPage();
        //PDF输出   I：在浏览器中打开，D：下载，F：在服务器生成pdf ，S：只返回pdf的字符串
        $nowDateCode=date("Ymd");
        $filName=ROOT_PATH.'public/uploads/pdf/'.$nowDateCode;
        $flag=false;
        if(!is_dir($filName)){
            $dir = iconv("UTF-8", "GBK", $filName);
            if (!file_exists($dir)){
                mkdir ($dir,0777,true);
                $flag=true;
            }
        }else{
            $flag=true;
        }
        if(!$flag){
            return array('code' => 0, 'msg' => '文件夹创建失败', 'data' => '');
        }
        $pdfName='/'.'down'.time().'.pdf';
//       $res=$pdf->Output('开标说明'.'.pdf', 'I');
        $res=$pdf->Output($filName.$pdfName, 'F');
        if(!$res){
            return array('code' => 1, 'msg' => '生成成功', 'data' => $nowDateCode.$pdfName);
        }
        return array('code' => 0, 'msg' => '生成成功', 'data' => '');
    }

    public  function getHtmlUser($data,$index){
//        var_dump($data);die();
        $color='#ffffff';
        if($index%2 == 0){
            $color='#eeeeee';
        }
        $leftData=array();$rightData=array();
        if(count($data)>=1){
            $leftData=is_array($data[0])?$data[0]:[];
        }
        if(count($data)>1){
            $rightData=is_array($data[1])?$data[1]:[];
        }
        //company_name,name_cn,name_en,mobile_person,label,positions_cn,positions_en
        $html="<tr><td colspan='6' style='padding:6px;'></td></tr>";
        $html.='<tr style="background-color: '.$color.'">';
        if(count($leftData)>0){
            $html.='<td width="17%">';
            $html.='<p style="font-size:11px;font-weight: bold;line-height: 18px;">'.$leftData['company_name'].'</p>';
            $html.='</td>';
            $html.='<td width="10%">';
            for($i=0;$i<count($leftData['child']);$i++){
                $html.='<p style="font-size:11px;margin:0;">'.($leftData['child'][$i]['name_cn']?$leftData['child'][$i]['name_cn']:$leftData['child'][$i]['name_en']).'</p>';
                $html.='<p style="font-size:11px;margin:0;line-height: 14px"></p>';
            }
            $html.='</td>';
            $html.='<td width="20%">';
            for($j=0;$j<count($leftData['child']);$j++){
                $html.='<p style="font-size:11px;margin:0;">'.($leftData['child'][$j]['positions_cn']?$leftData['child'][$j]['positions_cn']:$leftData['child'][$j]['positions_en']).'</p>';
                $html.='<p style="font-size:11px;margin:0;">'.$leftData['child'][$j]['email'].'</p>';
            }
            $html.='</td>';
        }
        $html.='<td style="background-color: #ffffff"  width="6%"><p style="height: 8px;"></p></td>';
        if(count($rightData)>0){
            $html.='<td width="17%">';
            $html.='<p style="font-size:11px;font-weight: bold;line-height: 18px;">'.$rightData['company_name'].'</p>';
            $html.='</td>';
            $html.='<td width="10%">';
            for($k=0;$k<count($rightData['child']);$k++){
                $html.='<p style="font-size:11px;margin:0">'.($rightData['child'][$k]['name_cn']?$rightData['child'][$k]['name_cn']:$rightData['child'][$k]['name_en']).'</p>';
                $html.='<p style="font-size:11px;margin:0;line-height: 14px"></p>';
            }
            $html.='</td>';
            $html.='<td width="20%">';
            for($m=0;$m<count($rightData['child']);$m++){
                $html.='<p style="font-size:11px;margin:0;">'.($rightData['child'][$m]['positions_cn']?$rightData['child'][$m]['positions_cn']:$rightData['child'][$m]['positions_en']).'</p>';
                $html.='<p style="font-size:11px;margin:0;">'.$rightData['child'][$m]['email'].'</p>';
            }
            $html.='</td>';
        }
        $html.='</tr>';
        return $html;
    }



}
